<template>
  <div>
    <el-button
      type="primary"
      icon="el-icon-plus"
      style="margin:10px 0px;0px"
      @click="isVisiable"
      >添加</el-button
    >
    <!-- 这个是表格 ElementUI的表格是一行一行的 -->
    <!-- 
      data:传递给表格的数据
      后面使用了作用域插槽从table表格中获取数据进行展示，结构由父组件决定，数据从table传递过来
     -->
    <el-table style="width: 100%" border :data="list">
      <el-table-column
        prop="prop"
        label="序号"
        width="80px"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column
        prop="tmName"
        label="品牌名称"
        width="width"
      ></el-table-column>
      <el-table-column prop="logoUrl" label="品牌LOGO" width="width">
        <template slot-scope="{ row }">
          <img
            v-lazy="row.logoUrl"
            :alt="row.logoUrl"
            style="width: 120px; height: 80px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{ row }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            @click="updateTrade(row, '修改品牌')"
            >修改</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="reqDeleteTradeMark(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 需要知道当前页，数据总条数，每页展示条数，连续页面数
         @size-change="handleSizeChange"   
      @current-change="handleCurrentChange" 当currentPage当前页码改变时触发
    -->
    <el-pagination
      @current-change="getPageList"
      @size-change="handleSizeChange"
      style="margin-top: 20px; text-align: center"
      background
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :page-size="limit"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
    >
    </el-pagination>

    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      style="width: 100%"
    >
      <el-form :model="tradeFrom" :rules="rules" ref="ruleForm">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input style="width: 80%" v-model="tradeFrom.tmName"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="tradeFrom.logoUrl"
              :src="tradeFrom.logoUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddOrUpdateTrade">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "tradeMark",
  data() {
    // 自定义品牌名称的校验规则
    const validateTradeName = (rule, value, callback) => {
      if (value.length < 2 || value.length > 10) {
        callback(new Error("品牌长度在2-10字符"));
      } else {
        callback();
      }
    };

    return {
      page: 1, //起始页码
      limit: 5, //连续展示的数据
      total: 0,
      list: [],
      title: "添加品牌",
      dialogFormVisible: false, //对话框是否可见

      //收集表单数据
      tradeFrom: {
        tmName: "",
        logoUrl: "",
      },

      rules: {
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          { validator: validateTradeName, trigger: "change" },
        ],
        logoUrl: [{ required: true, message: "请选择图片", trigger: "change" }],
      },
    };
  },

  mounted() {
    this.getPageList();
  },
  methods: {
    //发送请求获取数据在表单中展示
    async getPageList(pager = 1) {
      this.page = pager;
      const { page, limit } = this;
      try {
        let result = await this.$API.trademark.reqTradeMarkList(page, limit);
        this.total = result.data.total;
        this.list = result.data.records;
        console.log(result);
      } catch (error) {}
    },

    handleSizeChange(limit) {
      this.limit = limit;
      this.getPageList();
    },
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      console.log(res);
      if (res.code == 200) {
        this.tradeFrom.logoUrl = res.data;
      } else {
        this.$message({
          type: "warning",
          message: res.data,
        });
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    isVisiable() {
      this.dialogFormVisible = true;
      this.title = "添加品牌";
      //将之前存在的参数置空
      this.tradeFrom = { tmName: "", logoUrl: "" };
    },

    // 添加品牌
    AddOrUpdateTrade() {
      //表单合法性校验
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          //整理参数发送添加请求
          try {
            let result = await this.$API.trademark.reqAddOrUpdateTradeMark(
              this.tradeFrom
            );
            console.log("添加或者修改成功返回的数据", result);
            if (result.code == 200) {
              this.$message({
                type: "success",
                message: this.tradeFrom.id ? "修改品牌成功" : "添加品牌成功",
              });
              this.getPageList(this.tradeFrom.id ? this.page : 1);
            }
          } catch (error) {}
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //修改品牌信息
    updateTrade(row, title) {
      this.dialogFormVisible = true;
      this.tradeFrom = { ...row };
      this.title = title;
    },

    reqDeleteTradeMark(row) {
      this.$confirm("此操作将永久删除该该产品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let result = await this.$API.trademark.reqDeleteTradeMark(row.id);
          if (result.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getPageList(this.list.length > 1 ? this.page : this.page - 1);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
